#!/usr/bin/env python3
# dictionary_client.py
import socket
import json
import sys

SERVER_HOST = "127.0.0.1"
SERVER_PORT = 50000

def send_request(sock, req):
    data = (json.dumps(req) + "\n").encode('utf-8')
    sock.sendall(data)
    # 读取一行响应
    resp = b""
    while True:
        chunk = sock.recv(4096)
        if not chunk:
            return None
        resp += chunk
        if b"\n" in resp:
            line, _ = resp.split(b"\n",1)
            try:
                return json.loads(line.decode('utf-8').strip())
            except:
                return {"status":"error","message":"invalid response"}

def interactive_mode(server_host):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((server_host, SERVER_PORT))
        print(f"Connected to {server_host}:{SERVER_PORT}")
        print("Commands: lookup <word> | add <word> <translation> | list | quit")
        while True:
            try:
                line = input("> ").strip()
            except EOFError:
                break
            if not line:
                continue
            parts = line.split(maxsplit=2)
            cmd = parts[0].lower()
            if cmd == "quit":
                break
            if cmd == "lookup" and len(parts) >= 2:
                req = {"cmd":"lookup","word":parts[1]}
            elif cmd == "add" and len(parts) == 3:
                req = {"cmd":"add","word":parts[1],"translation":parts[2]}
            elif cmd == "list":
                req = {"cmd":"list"}
            else:
                print("Invalid command or parameters")
                continue
            resp = send_request(s, req)
            print("=>", resp)

if __name__ == "__main__":
    host = sys.argv[1] if len(sys.argv) >= 2 else SERVER_HOST
    interactive_mode(host)
